﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StyleMVVM.DependencyInjection.Impl;

namespace StyleMVVM.DependencyInjection
{
	/// <summary>
	/// Exported classes that use this attribute will be cached in the DI container and reused till the cache time expires
	/// </summary>
	public class CachedAttribute : Attribute, ILifeCycleContainerProviderAttribute
	{
		public CachedAttribute()
		{
			SlidingExpireWindow = true;
		}

		/// <summary>
		/// Allows you to control the length of time this component will be cached (15 min by default)
		/// Note: this string will be passed into a timespan so formats like "00:15:00" are expected
		/// </summary>
		public string ExpirationTime { get; set; }

		/// <summary>
		/// The cache window will be extended each time you access the object if true (true by default)
		/// </summary>
		public bool SlidingExpireWindow { get; set; }

		public ILifeCycleContainer ProvideContainer()
		{
			TimeSpan timeout;

			if (!TimeSpan.TryParse(ExpirationTime, out timeout))
			{
				timeout = new TimeSpan(0, 15, 0);
			}

			return new CachedLifeCycleContainer(SlidingExpireWindow, timeout);
		}
	}
}